package com.duan.learn.stream;

import com.duan.learn.stream.domain.User;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Jdk8StreamApi {

    /**
     * 获取所有成年的人，age >= 18
     * @param list
     * @return
     */
    public List<User> getAdultUser(List<User> list) {
        return list.stream().filter(v -> v.getAge() >= 18).collect(Collectors.toList());
    }

    /**
     * 获取所有成年的姓名
     * @param list
     * @return
     */
    public List<String> getAdultName(List<User> list) {
        return list.stream().filter(v -> v.getAge() >= 18).map(User::getName).collect(Collectors.toList());
    }

    /**
     * 获取所有对象的名称
     * @param list
     * @return
     */
    public List<String> getUserNameList(List<User> list) {
        return list.stream().map(User::getName).collect(Collectors.toList());
    }

    /**
     * 获取所有的用户名，以逗号分隔
     * @param list
     * @return
     */
    public String getUserNames(List<User> list) {
        return list.stream().map(User::getName).collect(Collectors.joining(","));
    }

    /**
     * 获取所有用户的ID，以逗号分隔
     * @param list
     * @return
     */
    public String getUserIds(List<User> list) {
        return list.stream().map(User::getId).map(String::valueOf).collect(Collectors.joining(","));
    }

    /**
     * 按年龄分组，年龄相同的用户名廉洁
     * @param list
     * @return
     */
    public Map<Integer, String> getNamesByAge(List<User> list) {
        Map<Integer, String> map = list.stream().collect(
                Collectors.toMap(User::getAge, User::getName, (String existName, String toAddName) -> existName + "," + toAddName));
        return map;
    }

    /**
     * 去掉重复的名字
     * @param names
     * @return
     */
    public Set<String> list2Set(List<String> names) {
        return names.stream().collect(Collectors.toSet());
    }

    /**
     * 跳过前n个
     * @param names
     * @param n
     * @return
     */
    public List<String> skip(List<String> names, int n) {
        return names.stream().skip(n).collect(Collectors.toList());
    }

    /**
     * 只取前n个
     * @param names
     * @param n
     * @return
     */
    public List<String> limit(List<String> names, int n) {
        return names.stream().limit(n).collect(Collectors.toList());
    }

    /**
     * 取m后的n个
     * @param names
     * @param n
     * @param m
     * @return
     */
    public List<String> skipAndLimit(List<String> names, int n, int m) {
        return names.stream().skip(m).limit(n).collect(Collectors.toList());
    }
}
